package com.iaiai.notepad;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.gesture.Gesture;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.MotionEvent;
import android.widget.EditText;

import com.iaiai.notepad.util.ImageUtil;

public class GesturesProcessor implements GestureOverlayView.OnGestureListener {
	
	private Gesture mGesture;
	
	private Timer timer;
	
	private TimerTask task;
	
	private Handler handler = new Handler();
	
	private int img = 0;
	
	private EditText edit;
	
	public GesturesProcessor(EditText edit,Gesture mGesture){
		this.mGesture = mGesture;
		this.edit = edit;
	}
	
	public void onGestureStarted(GestureOverlayView overlay,
			MotionEvent event) {
		mGesture = null;
		if(task!=null)task.cancel();
		if(timer!=null)timer.cancel();
	}
	
	public void onGesture(GestureOverlayView overlay, MotionEvent event) {
		
	}
	
	public void onGestureEnded(final GestureOverlayView overlay, MotionEvent event) {
		// 获取在GestureOverlayView手势
		mGesture = overlay.getGesture(); // 注2
		
		timer = new Timer();
		task = new TimerTask() {
			public void run () {
				handler.post(new Runnable() {
					public void run() {
						Bitmap b=mGesture.toBitmap(30, 30, 0, Color.BLACK);
						
						ImageGetter imageGetter = new ImageGetter(){
							@Override  
							public Drawable getDrawable(String source){
								Bitmap b=mGesture.toBitmap(30, 30, 0, Color.BLACK);
								Drawable d = new BitmapDrawable(b);
								d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
								return d;
							}
						};
						
						String filename = "/sdcard/Notepad/img/"+UUID.randomUUID().toString()+".png";
						
						try {
							ImageUtil.saveImageByBitmap(b, filename);
						} catch (IOException e) {
							e.printStackTrace();
						}
						
						edit.getEditableText().insert(edit.getSelectionStart(), Html.fromHtml("<img src='"+filename+"'/>", imageGetter, null));
						
						overlay.setFadeOffset(10);//清除前设置时间间隔缩小
						overlay.clear(true);
						overlay.setFadeOffset(800);//清楚后恢复时间间隔
					}
				});
			}
		};
		timer.schedule(task,500);
	}

	public void onGestureCancelled(GestureOverlayView overlay,
			MotionEvent event) {
	}

}
